﻿using Authentication.Model.Interface;
using Authentication.Model.Model;
using Common.Contract;
using Common.Contract.Authentication;
using Common.Contract.Authentication.Identifier;
using Common.Contract.Authentication.Request;
using Common.Service.Command;
using Common.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Authentication.ServiceCommand
{
    public class SaveGroupRolesServiceCommand : ProviderServiceCommand<IGroupRoleProvider, SaveGroupRolesRequest, ResponseRecord>
    {
        public SaveGroupRolesServiceCommand(IGroupRoleProvider providers) : base(providers) { }
        protected override void Validate(SaveGroupRolesRequest request)
        {
            if (request == null) throw new ArgumentNullException("request");
            if (!request.Header.ApplicationKey.HasValue || request.Header.ApplicationKey == Guid.Empty)
            {
                throw new ArgumentException("ApplicationKey must be set", "request");
            }
            if (request.Record == null || request.Record.Count == 0)
            {
                throw new ArgumentException("Record must be set", "request");
            }
            //if (!RoleIdentifier.IsValid(request.Record.GroupIdentifier))
            //{
            //    throw new ArgumentException("RoleIdentifier is invalidate", "request");
            //}
        }

        protected override bool OnExecute(ResponseRecord response)
        {
            var applicationKey = Request.Header.ApplicationKey.ToString().ToUpper();
            bool result = true;
            foreach (var record in Request.Record)
            {
                var roleid = -1;
                if (RoleIdentifier.IsValid(record.RoleIdentifier)) roleid = new RoleIdentifier(record.RoleIdentifier).PersistableID;
                var group = new ApplicationGroupRule
                {
                    ApplicationKey = applicationKey,
                    GroupId = record.GroupIdentifier,
                    ObjectId = record.ObjectIdentifier,
                    RuleId = roleid,
                    Active = (record.Active ?? false).ToBooleanString(),
                };

                var isSaved = Providers.Update(group);
                if (!isSaved) result = false;
            }
            return result;
        }
    }
}
